package com.duo.service.impl;

import com.duo.constant.GlobalConstant;
import com.duo.dto.ShoppingCartCacheDTO;
import com.duo.dto.ShoppingCartDTO;
import com.duo.service.ShoppingCartService;
import com.duo.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: Xrx
 * @Description:
 * @CreateTime: 2023/7/8 20:55
 */
@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 添加购物车
     */
    @Override
    public void addShoppingCart(List<ShoppingCartDTO> shoppingCartDTOList, Long userId) {
        String key = GlobalConstant.DISH_PREFIX + userId;
        List<ShoppingCartCacheDTO> shoppingCart = shoppingCartDTOList.stream().map(shoppingCartDTO -> {
            ShoppingCartCacheDTO shoppingCartCacheDTO = new ShoppingCartCacheDTO();
            BeanUtils.copyProperties(shoppingCartDTO, shoppingCartCacheDTO);
            shoppingCartCacheDTO.setUserId(userId);
            shoppingCartCacheDTO.setAmount(shoppingCartDTO.getPrice().multiply(new BigDecimal(shoppingCartDTO.getNumber())));
            return shoppingCartCacheDTO;
        }).collect(Collectors.toList());
        redisUtils.setCacheList(key, shoppingCart, GlobalConstant.DISH_EXPIRE_TIME, TimeUnit.MINUTES);
        log.info("添加购物车成功");
    }

    /**
     * 查看购物车中所有的商品
     * @return
     */
    @Override
    public List<ShoppingCartCacheDTO> showShoppingCart(Long userId) {
        String key = GlobalConstant.DISH_PREFIX + userId;
        List<ShoppingCartCacheDTO> cacheList = redisUtils.getCacheList(key);
        log.info("查看购物车成功, {}", cacheList);
        return cacheList;
    }

    /**
     * 清空购物车
     */
    @Override
    public void cleanShoppingCart(Long userId) {
        String key = GlobalConstant.DISH_PREFIX + userId;
        redisUtils.deleteObject(key);
        log.info("清空购物车成功");
    }


}
